//
//  UpdateTelViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/26.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "UpdateTelViewController.h"
#import "UpdateTelSuccessViewController.h"

//Cell
#import "UpdateTelCell.h"

//Request
#import "HTTPPromise+Login.h"

//Tools
#import "AppUtil.h"

@interface UpdateTelViewController ()<UITableViewDelegate,UITableViewDataSource,UpdateTelDelegate>
@property (strong, nonatomic) IBOutlet UITableView *updateTelTableView;

@end

@implementation UpdateTelViewController
#pragma mark -init
#define UpdateTelCellIdentifyCell  @"UpdateTelCell"

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UINib *xib = [UINib nibWithNibName:NSStringFromClass([UpdateTelCell class])
                                bundle:[NSBundle mainBundle]];
    [self.updateTelTableView registerNib:xib forCellReuseIdentifier:UpdateTelCellIdentifyCell];
    [self initTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:0];
    [self addNavigationMiddleView:@"修改手机号"];
}

- (void)initTableView{
    _updateTelTableView.tableFooterView = [[UIView alloc] init];
    _updateTelTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _updateTelTableView.scrollEnabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row != 2){
        UpdateTelCell *telCell = [tableView dequeueReusableCellWithIdentifier:UpdateTelCellIdentifyCell];
        
        telCell.selectionStyle = UITableViewCellSelectionStyleNone;
        telCell.telDelegate = self;
        [telCell configureCell:(int)indexPath.row];
        
        return telCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        nextBtn.frame = CGRectMake((SCREEN_WIDTH - 200) / 2, 9.5, 200, 25);
        [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [nextBtn setBackgroundColor:HTCFQuickRGBColor(51,190,0)];
        [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [nextBtn addTarget:self action:@selector(skipRequest) forControlEvents:UIControlEventTouchUpInside];
        
        [cell addSubview:nextBtn];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
    return 10;
}

#pragma mark -action
- (void)skipRequest{
    UITextField *telText = [_updateTelTableView viewWithTag:200];
    UITextField *verifyText = [_updateTelTableView viewWithTag:201];
    NSString *telString = telText.text;
    if(!HTCFVerifyPhoneNumber(telString)){
        [AppUtil showTipMessage:@"请输入正确11位手机号码"];
        return ;
    }
    NSString *verifyString = verifyText.text;
    if(!HTCFVerifyCode(verifyString)){
        [AppUtil showTipMessage:@"请输入正确验证码"];
        return ;
    }
    NSDictionary *doctorParam = @{@"mobile":telString,@"verificationCode":verifyString};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:doctorParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:doctorParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requesBindMobileParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        
        if (successRet == 0) {
            [strongSelf skipController:telString];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)skipController:(NSString *)telephone{
    HTCFUDFCache(kMobileKey,telephone);
    mobileStr = HTCFUDFGetValue(kMobileKey);
    
    UpdateTelSuccessViewController *sucessVC = [[UpdateTelSuccessViewController alloc] init:mobileStr];
    [self.navigationController pushViewController:sucessVC animated:YES];
}

#pragma mark -UpdateTelDelegate
- (void)sendTel{
    UITextField *telText = [_updateTelTableView viewWithTag:200];
    NSString *telString = telText.text;
    if(!HTCFVerifyPhoneNumber(telString)){
        [AppUtil showTipMessage:@"请输入正确11位手机号码"];
        return ;
    }
    NSDictionary *telParam = @{@"mobile":telString};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:telParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:telParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    [HTTPPromise requesSendCodeParams:jsonData Success:^(id responseObj) {
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];
        
        if (successRet != 0) {
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
